package com.sqgxy.controller;

import com.sqgxy.service.FileService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@RestController
@RequestMapping("/file")
public class FileController {
    private final FileService fileService;

    public FileController(FileService fileService) {
        this.fileService = fileService;
    }

    /**
     * 收到文件将文件重命名（UUID）
     * 按照日期保存到服务器文件系统不同的目录中(目录格式 yyyyMMdd)
     * 将文件大小、文件类型，原始文件名，创建时间，文件保存目录地址等元数据记录至数据库中
     * @param file 上传的文件
     * @param request 请求信息
     * @return UUID返回给客户端
     */
    @PostMapping("/upload")
    @ResponseBody
    public String upload(MultipartFile file, HttpServletRequest request) {
        if (file == null) return "请上传文件";
        return fileService.upload(file, request);
    }

    /**
     * 获取文件流，客户端参数为UUID，在响应中写入文件流，无其他返回值，异常返回410
     * @param id 文件的uuid值
     */
    @GetMapping("/download")
    public void download(HttpServletRequest request, HttpServletResponse response, String id) {
        if ("".equals(id)) return;

        fileService.download(id);
        // 返回的直接是path,全路径
        String path = fileService.download(id);

        File file = new File(path);
        InputStream in = null;
        try {
            in = new FileInputStream(file);
            int len = 0;
            int count = 0;
            byte buffer[] = new byte[1024];
            OutputStream out = response.getOutputStream();
            while ((len = in.read(buffer)) != -1) {
                count += len;
                out.write(buffer, 0, len);
            }
            System.out.println(count);
        } catch (IOException e) {
            e.printStackTrace();
            response.setStatus(410);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 客户端参数为UUID，返回值为json格式的元数据信息
     * @param id 文件的uuid值
     *  返回json格式的元数据
     */
    @GetMapping("/getDate")
    public String getDate(String id, HttpServletResponse response) {
        String date = fileService.getDate(id);
        /*System.out.println(date);
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.write(date);
        } catch (IOException e) {
            e.printStackTrace();
        }*/
        return date;
    }
}
